let role = [
	{id: 1, name: '1栋', houNum: '一栋信息介绍',user: '小张'},
	{id: 2, name: '2栋', houNum: '二栋信息介绍',user: '小王'},
	{id: 3, name: '5栋', houNum: '五栋信息介绍',user: '小赵'},
	{id: 4, name: '8栋', houNum: '八栋信息介绍',user: '明儿'},
];

let house = JSON.parse(localStorage.getItem("house"));
if(!house) {
	house = role;
	saveData2Storage();
}
let table = document.getElementsByTagName("table")[0];
let tbody = table.getElementsByTagName("tbody")[0];

//模拟登录成功
// sessionStorage.setItem("account", "hehe");
let $tbody = $("table").find("tbody");

//清除
function clear() {
	do{
		tbody.removeChild(tbody.firstChild);
	}while(tbody.hasChildNodes());
}

/**
 * init初始化函数
 */
function init() {
	//绑定事件
	$("#btn_search").click(search);
	$("#btn_delSelected").click(delSelected);
	$("input[name='cb_select_all']").change(selectAll);
	$tbody.find("tr").dblclick(rowEdit);//双击事件
	$("#btn_rowEdit").click(save);
}

function saverow() {
	if(!editTr) {
		return;
	}
	console.log(editTr);
	let editData = null;//当前被编辑的数据
	let editDataId = editTr.find("input[name='cb_select']").val();
	let editIndex = 0;
	for(let index in house) {
		let item = house[index];
		if(item.id === parseInt(editDataId)) {
			editData = item;
			editIndex = index;
			break;
		}
	}
	
	//获取重置的id
	var obj = event.srcElement;
	var elementId = obj.id;
	console.log(elementId);
	
	editTr.children().each(function(index, item) {
		if(this.title === "noedit1") {
			let td1 = $(this);
			td1.html(`
				<button type="button" onclick="toLook(${index})" data-toggle="modal" data-target="#modal_add" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">查看信息</button>
				<button type="button" onclick="toEdit(${index})" data-toggle="modal" data-target="#modal_add" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">修改</button>
				<button onclick="del(${index})" style="border-radius: 6px;color:#fff;background-color: red;border: 1px solid red;">删除</button>
			`);
		}
		if(this.title !== "noedit1") {
			//获取td中输入框
			let input = $(item).find("input");
			//获取input中value
			let value = input.val();
			//重置按钮
			if(elementId === "toRes"){
				value = input.val("");
				return;
			}
			//删除input
			input.remove();
			//将value添加到td中
			$(item).text(value);
			//将input中值绑定到对象的属性上
			if(typeof editData[this.title] === "number") {
				//整型和浮点型
				if(value.indexOf(".") != -1) {
					editData[this.title] = parseFloat(value);
				}else {
					editData[this.title] = parseInt(value);
				}
			}else {
				editData[this.title] = value;
			}
		}
	});
	//实现数据保存到数组中
	// console.log(editData);
	house.splice(editIndex, 1, editData);
	//将数组更新到localStorage中
	saveData2Storage();
}

function saveData2Storage() {
	localStorage.setItem("house", JSON.stringify(house));
}

let editTr;//作用域是在整个script标签中

//退出行编辑
function rowEdit() {
	$("#btn_rowEdit").show();
	editTr = $(this);
	//$(this)：表示的是tr
	$(this).children().each(function(index, item) {
		if(this.title === "noedit1") {
			let td1 = $(this);
			td1.html(`
				<button type="button" onclick="saverow(${index})" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">保存</button>
				<button id="toRes" onclick="saverow(${index})" style="border-radius: 6px;color:#fff;background-color: red;border: 1px solid red;">重置</button>
			`);
		}
		if(this.title !== "noedit1" && $(this).find("input").length === 0) {
			//将td中内容获取保存
			let td = $(this);
			//此时使用$(this)，表示td
			let text = $(this).text();
			//将td中的内容清空
			$(this).text("");
			//在td里面插入一个input
			let input = document.createElement("input");
			input.type = "text";
			input.value = text;
			let widthValue = 20 * text.length;
			input.style = "width: " + widthValue + "px";
			//添加到td中
			$(this).append(input);
			console.log(this);
		}
	});
}

// function toRes(){
// 	$('#yigeform')[0].reset();
// }

//全选
function selectAll() {
	$("input[name='cb_select']").prop("checked", $(this).prop("checked"));
}

//批量删除
function delSelected() {
	//获取所有选中name为cb_select的checkbox
	obj = document.getElementsByName("cb_select");
	check_val = [];
	for(k in obj){
		if(obj[k].checked)
			check_val.push(obj[k].value);
	}
	if(check_val.length === 0){
		if(!confirm("请选择要删除的数据！")){
			return;
		}
	}else{
		if(!confirm("确定要删除这" + check_val.length + "条数据吗？")){
			return;
		}
	}
	$("input[name='cb_select']:checked").each(function(index, item) {
		for(let i in house) {
			let houseItem = house[i];
			if(parseInt($(item).val()) === houseItem.id) {
				house.splice(i, 1)
			}
		}
	});
	$tbody.empty();
	update();
	saveData2Storage();
}

//单行删除
function del(index) {
	let result = confirm("确认是否删除这条记录？");
	if(!result) {
		return;
	}
	//删除数组中的数据
	house.splice(index,1);
	clear();
	saveData2Storage();
	$tbody.empty();
	update();
}

//查看信息
function toLook(index){
	let item = house[index];
	sessionStorage.setItem("index", index);
	sessionStorage.setItem("item", JSON.stringify(item));
	$("#name").text(item.name);
	$("#houNum").text(item.houNum);
	$("#user").text(item.user);
}

//编辑
function toEdit(index) {
	let item = house[index];
	sessionStorage.setItem("index", index);
	sessionStorage.setItem("item", JSON.stringify(item));
	$("input[name='name']").val(item.name);
	$("input[name='houNum']").val(item.houNum);
	$("input[name='user']").val(item.user);
}

//添加
function toAdd(){
	sessionStorage.removeItem("index");
	sessionStorage.removeItem("item");
	$('.form-control').val("");
}

/**
 * 找出books对象数组中id最大的id值
 * @param {Object} arr
 */
function maxId(arr) {
	console.log(typeof arr);
	if(arr instanceof Array) {
		if(arr.length === 0) {
			return;
		}
		let max = arr[0];
		for(let item of arr) {
			if(max.id < item.id) {
				max = item;
			}
		}
		
		return max.id;
	}
}
 //修改或添加的保存	
function save() {
	let editItem = JSON.parse(sessionStorage.getItem("item"));
	let name = $("input[name='name']").val();
	let houNum = $("input[name='houNum']").val();
	let user = $("input[name='user']").val();
	let obj = {
		id: editItem ? editItem.id : 1,
		name: name,
		houNum: houNum,
		user: user
		// count: editItem ? editItem.count : 1,
		// account: sessionStorage.getItem("account")
	}
	
	//获取数组
	let house = localStorage.getItem("house");
	
	if(house) {
		house = JSON.parse(house);
		//判断用户名是否重复
		for(let index in house) {
			let item = house[index];
			// if(sessionStorage.getItem("account") !== item.account) {
			// 	continue;
			// }
			if(editItem) {
				//编辑
				if(editItem.user !== user && item.user === user) {
					alert("用户名不能重复");
					return;
				}
			}else{
				//添加
				if(item.user === user) {
					alert("用户名不能重复");
					return;
				}
			}
		}
		if(editItem) {
			let index = sessionStorage.getItem("index");
			house.splice(index, 1, obj)
		}else {
			obj.id = maxId(house) + 1;
			house.push(obj);//添加
		}
		//放回去
		localStorage.setItem("house", JSON.stringify(house));
		
		//页面跳转
		location.href = 'MainHouse.html';
	}
}

//搜索
function search() {
	let name = ipt_name.value;
	if(name.trim().length === 0) {
		alert("请输入查询条件")
		return;
	}
	clear();
	update({name});
}

//数据显示
function update(args) {
	//不需要使用break或continue等操作，可以使用$.each
	for(let index in house){
		let item = house[index];
		// console.log(item);
		//console.log(sessionStorage.getItem("loginAccount"))
		// if(sessionStorage.getItem("account") !== item.account) {
		// 	continue;
		// }
		// if(bookName && item.name.toLowerCase().indexOf(bookName.toLowerCase()) === -1) {
		// 	continue;
		// }
		//搜索功能
		if(args) {
			if(args.name.trim().length !== 0 && item.name !== args.name) {
				continue;
			}
		}

		let tr = `
			<tr>
				<td title="noedit" style="text-align: center;"><input type="checkbox" name="cb_select" value="${item.id}"/></td>
				<td title="id">${item.id}</td>
				<td title="name">${item.name}</td>
				<td title="houNum">${item.houNum}</td>
				<td title="user">${item.user}</td>
				<td title="noedit1">
					<button type="button" onclick="toLook(${index})" data-toggle="modal" data-target="#modal_add1" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">查看信息</button>
					<button type="button" onclick="toEdit(${index})" data-toggle="modal" data-target="#modal_add" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">修改</button>
					<button onclick="del(${index})" style="border-radius: 6px;color:#fff;background-color: red;border: 1px solid red;">删除</button>
				</td>
			</tr>
		`;
		$tbody.append(tr);
	}
}
update();
init();

//分页
$(function() {
	$("#mytable").DataTable({
		"searching": false, //是否启用搜索
		"sPaginationType": "full_numbers",// 分页，一共两种样式,一种full_numbers 另一种为two_button // 是housetables默认
		"bPaginate": true, //翻页功能 分页按钮
		"bLengthChange": false,//是否允许终端用户从一个选择列表中选择分页的页数，页数为10，25，50和100，需要分页组件bPaginate的支持
		"bFilter": false,//是否对数据进行过滤，搜索栏
		"bSort": false,//是否开启列排序
		"iDisplayLength": 5,//单页显示的数据的条数

		
		"oLanguage": {
		"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
		"sInfoEmpty": "没有数据",
		"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
		"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "上一页",
			"sNext": "下一页",
			"sLast": "尾页"
		},
		// "sZeroRecords": "没有检索到数据",
		// "sProcessing": "<img src='./loading.gif' />",
		// "sSearch": "搜索"
		},
	})
})
